//
//  YCQRScanSelfViewController.m
//  DemoQRCode
//
//  Created by yunsheng on 15/7/14.
//  Copyright (c) 2015年 yunsheng. All rights reserved.
//

#import "YCQRScanSelfViewController.h"

#import <AVFoundation/AVFoundation.h>

#define IOS7_OR_LATER   ( [[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending )

@interface YCQRScanSelfViewController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic, strong) AVCaptureSession *session;        ///< 二维码生成的绘画
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; ///< 二维码生成的图层

@end

@implementation YCQRScanSelfViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.qrScanResLabel.numberOfLines = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewDidAppear:(BOOL)animated
{
    [self readQRCode];
    [super viewDidAppear:animated];
}

-(void)dealloc
{
    [self.session stopRunning];
    [self.previewLayer removeFromSuperlayer];
}

#pragma mark - 二维码

- (void)readQRCode
{
    if (IOS7_OR_LATER) {
        // 摄像头设备
        AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        // 设置输入
        NSError* error = nil;
        AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
        if (error) {
            NSLog(@"没有摄像头--%@", error);
            return;
        }
        // 设置输出
        AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc] init];
        // 设置输出的代理, 说明：使用主线程队列，相应比较同步，使用其他队列，相应不同步，容易让用户产生不好的体验
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        //[output setMetadataObjectsDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
        
        // 拍摄会话
        AVCaptureSession * session = [[AVCaptureSession alloc] init];
        //// 添加session的输入和输出
        [session addInput:input];
        [session addOutput:output];
        
        // 设置输出的格式
        [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
        // 设置预览图层（用来让用户能够看到扫描情况）
        AVCaptureVideoPreviewLayer * preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
        //// 设置preview图层的属性
        [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        //// 设置preview图层的大小
        [preview setFrame:self.qrPreView.bounds];
        //// 将图层添加到视图的图层
        [self.qrPreView.layer insertSublayer:preview atIndex:0];
        self.previewLayer = preview;
        
        // 启动会话
        [session startRunning];
        self.session = session;
    } else {
        
    }
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    // 会频繁的扫描，调用代理方法
//    // 1. 如果扫描完成，停止会话
//    [self.session stopRunning];
//    // 2. 删除预览图层
//    [self.previewLayer removeFromSuperlayer];
    
    NSLog(@"%@", metadataObjects);
    // 3. 设置界面显示扫描结果
    
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        // 提示：如果需要对url或者名片等信息进行扫描，可以在此进行扩展！
        self.qrScanResLabel.text = obj.stringValue;
    }
}

@end
